package com.fingard.dsp.bank.directbank.gac01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Parker on 2020-06-18.
 * @version 1.0
 */
public class GAC01Transaction extends GAC01Base implements ITransaction {
    protected List<String> receiptCodes = new ArrayList<String>();
    protected boolean isFromReceiptQry = false;

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        StringBuilder tmpRespInfo = new StringBuilder();
        try {
            String transCode = "3";

            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("Iss_Itreasury");
                xmlWriter.writeStartElement("QueryReq");
                xmlWriter.writeElementString("OperationType", transCode);//操作类型
                xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
                xmlWriter.writeStartElement("QueryContent");
                xmlWriter.writeElementString("AccountCode", p_req7516.actNum);//账号
                xmlWriter.writeElementString("ExcuteStart", Format.Date10Format.format(tmpCalendarFrom.getTime()));//开始日期
                xmlWriter.writeElementString("ExcuteEnd", Format.Date10Format.format(tmpClndrStepTo.getTime()));//结束日期
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7516.reqHeader.transType, p_req7516.reqHeader.transType);

                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/ApplyCode");
                        String returnMsg = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
                        if (StringHelper.isNullOrEmpty(returnCode)) {
                            while (tmpBkReader.read("/Iss_Itreasury/QueryRen/RenContent")) {
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                XElement tmpRecord = tmpBkReader.readedXElement;
                                tmpRetDetail.actNum = tmpRecord.getSingleText("AccountNo");
                                tmpRetDetail.recAccNum = tmpRecord.getSingleText("OppAccountNo");//对方账号
                                tmpRetDetail.recAccName = tmpRecord.getSingleText("OppAccountName");//对方户名
                                tmpRetDetail.tranAmt = tmpRecord.getSingleText("Amount");//交易金额
                                tmpRetDetail.cdFlag = tmpRecord.getSingleText("TransDirection");//1付款2收款
                                String tranDate = tmpRecord.getSingleText("ExcutDate");//交易日期yyyyMMdd
                                tmpRetDetail.tranDate = DateHelper.convertD8toD10(tranDate);
                                tmpRetDetail.tranTime = tranDate + " 00:00:00";
                                tmpRetDetail.valueDate = DateHelper.convertD8toD10(tmpRecord.getSingleText("InterestStart"));//起息日
                                tmpRetDetail.usage = tmpRecord.getSingleText("Purpose");
                                tmpRetDetail.abstr = tmpRecord.getSingleText("Note");//摘要（对账码）
                                tmpRetDetail.bnkSeqNo = tmpRecord.getSingleText("TransNo");//银行流水号, 用于回单匹配
                                tmpRetDetail.accBal = tmpRecord.getSingleText("CurrentBalance");//交易后账户余额
                                if (isFromReceiptQry && StringHelper.hasAnyChar(tmpRetDetail.bnkSeqNo)) {
                                    receiptCodes.add(tmpRetDetail.bnkSeqNo);
                                }
                                nodeAnalysic(tmpRecord, tmpRetDetail, getCharset());//根据配置将 note 分割赋值给对账码和用途
                                retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                            }
                        } else {
                            tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                                    .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(returnMsg + "\r\n");
                        }
                    } else {
                        tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                                .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(tmpSbMsg.toString() + "\r\n");
                    }
                } else {
                    tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                            .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(tmpRetBkStr[1] + "\r\n");
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
            e.printStackTrace();
            retAts.writeRespCode("-1");
            tmpRespInfo.append("查询异常：").append(e.getMessage()).append("\r\n");
            retAts.writeRespInfo(tmpRespInfo.toString());
        } finally {
            if (tmpRespInfo.length() > 0) {
                WriteBankLogLn(tmpRespInfo.toString());
            }
        }
        if (retAts.getWrittenRdCount() == 0 && tmpRespInfo.length() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        } else if (tmpRespInfo.toString().length() > 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo(tmpRespInfo.toString());
        } else {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("查询成功");
        }
        retAts.writeEndWithoutInsertDB();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
//        //历史明细查询返回ATS的对象
//        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
//        retAts.writeStart();//写返回ATS的统一头部信息
//        StringBuilder tmpRespInfo = new StringBuilder();
//        try {
//            String transCode = "7";
//            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
//            writeCommonHeader(xmlWriter);
//            xmlWriter.writeStartElement("Iss_Itreasury");
//            xmlWriter.writeStartElement("QueryReq");
//            xmlWriter.writeElementString("OperationType", transCode);//操作类型
//            xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
//            xmlWriter.writeStartElement("QueryContent");
//            xmlWriter.writeElementString("AccountCode", p_req7515.actNum);//账号
//            xmlWriter.writeEndDocument();
//
//            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7515.reqHeader.transType, p_req7515.reqHeader.transType);
//
//            if (tmpRetBkStr[0].length() == 0) {
//                StringBuilder tmpSbMsg = new StringBuilder();
//                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
//                if (tmpBkReader != null) {
//                    String returnCode = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/ApplyCode");
//                    String returnMsg = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
//                    if (StringHelper.isNullOrEmpty(returnCode)) {
//                        while (tmpBkReader.read("/Iss_Itreasury/QueryRen/RenContent/")) {
//                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
//                            XElement tmpRecord = tmpBkReader.readedXElement;
//                            tmpRetDetail.actNum = tmpRecord.getSingleText("AccountNo");
//                            tmpRetDetail.recAccNum = tmpRecord.getSingleText("OppaccountNo");//收方账号
//                            tmpRetDetail.recAccName = tmpRecord.getSingleText("OppaccountName");//收方户名
//                            tmpRetDetail.tranAmt = tmpRecord.getSingleText("Amount");//交易金额
//                            tmpRetDetail.cdFlag = tmpRecord.getSingleText("TransDirection");//借贷标志 D:借 C:贷
//                            String tranDate = tmpRecord.getSingleText("ExcutDate");//交易日期yyyyMMdd
//                            tmpRetDetail.tranDate = DateHelper.convertD8toD10(tranDate);
//                            tmpRetDetail.tranTime = tranDate + " 00:00:00";
//                            tmpRetDetail.usage = tmpRecord.getSingleText("UseInfo");
//                            tmpRetDetail.abstr = tmpRecord.getSingleText("Note");//摘要（对账码）
//                            tmpRetDetail.bnkSeqNo = tmpRecord.getSingleText("TransNo");//银行流水号, 用于回单匹配
//                            nodeAnalysic(tmpRecord, tmpRetDetail, getCharset());//根据配置将 note 分割赋值给对账码和用途
//                            retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
//                        }
//                    } else {
//                        tmpRespInfo.append("查询账号").append(p_req7515.actNum).append("今日明细失败,原因:").append(returnMsg + "\r\n");
//                    }
//                } else {
//                    tmpRespInfo.append("查询账号").append(p_req7515.actNum).append("今日明细失败,原因:").append(tmpSbMsg.toString() + "\r\n");
//                }
//            } else {
//                tmpRespInfo.append("查询账号").append(p_req7515.actNum).append("今日明细失败,原因:").append(tmpRetBkStr[1] + "\r\n");
//            }
//            if (retAts.getWrittenRdCount() == 0 && tmpRespInfo.length() == 0) {
//                retAts.writeRespCode("0");
//                retAts.writeRespInfo("交易为空");
//            } else if (tmpRespInfo.toString().length() > 0) {
//                retAts.writeRespInfo(tmpRespInfo.toString());
//            } else {
//                retAts.writeRespInfo("查询成功");
//            }
//        } catch (Exception e) {
//            WriteBankLogLn(e);
//            e.printStackTrace();
//            retAts.writeRespCode("-1");
//            tmpRespInfo.append("查询异常：").append(e.getMessage()).append("\r\n");
//            retAts.writeRespInfo(tmpRespInfo.toString());
//        } finally {
//            if (tmpRespInfo.length() > 0) {
//                WriteBankLogLn(tmpRespInfo.toString());
//            }
//        }
//        retAts.writeEndWithoutInsertDB();
//        return retAts;
    }
}
